#include <stdio.h>
#include <stdint.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include "di_rw.h"
#include "di_test.h"
#include "thread_ctrl.h"
#include "ietDiLib.h"

void irq_callback(int channel, int type, int data)
{
    printf("DI %2d capture edge %d level %d\n", channel, type, data);
}

/* 接收 DI 数据线程函数 */
void *recv_di_thread(void *arg)
{
    struct di_dev_t *pdev = (struct di_dev_t *)arg;
    struct di_param_t *pparam = (struct di_param_t *)pdev->parent;
    struct thread_param_t *pthread = pdev->read_thread;
    int ret = 0;
    int i = 0;
    struct DimParam devParam = {
        .mode = pdev->mode,
        .type = pdev->edge,
        .window = pdev->delay,
    };

    /* 检查参数是否有效 */
    if (!pthread || !pthread->name) {
        fprintf(stderr, "Invalid parameters for %s\n", __func__);
        return NULL;
    }

    /* 线程取消 SIGUSR1 的阻塞 */
    init_thread_user_signal();
    /* 配置 DI 参数 */
    if (devParam.mode == 1) {
        registerCallback(pdev->index, irq_callback);
    }
    DIMInit(pdev->index, devParam);
    // printf("Start %s receive thread...\n", pdev->path);
    while (!pthread->exit_sig) {
        for (i = 0; (pparam->read_cnt == -1 || i < pparam->read_cnt) && !pthread->exit_sig; i++) {
            switch (pdev->mode) {
            case DI_MOD_LEVEL:
                /* 获取 DI 数值 */
                ret = DIMRead(pdev->index, (int *)&pdev->level);
                if (ret < 0) {
                    fprintf(stderr, "DIMRead DI %2d failed\n", pdev->index);
                    return NULL;
                }
                printf("DIMRead DI %2d level %d\n", pdev->index, pdev->level);
                break;
            case DI_MOD_IRQ:
                break;
            default:
                fprintf(stderr, "Read %s failed, mode=%d not support\n", pdev->path, pdev->mode);
                break;
            }
        }
        // printf("Read %s %d data done\n", pdev->path, pparam->read_cnt);
        break;
    }
    // printf("%s %s return\n", pdev->path, __func__);

    return NULL;
}
